package com.kmzx.gen.signs.api.impl;

import com.kmzx.gen.signs.api.FileApi;
import com.kmzx.gen.signs.config.GateProfileConfig;
import com.kmzx.gen.signs.dao.PushDataMapper;
import com.kmzx.gen.signs.dto.BackToRecord;
import com.kmzx.gen.signs.entity.PushData;
import com.kmzx.gen.signs.utils.UUID;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import weixin.popular.client.LocalHttpClient;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Project gen_sign
 * @Author: carol
 * @Date: 2020/7/21-18:19
 */
@Service
public class FileApiImpl implements FileApi {

    private static Logger logger = LoggerFactory.getLogger(FileApiImpl.class);


    protected static Header xmlHeader = new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.create("application/xml", "UTF-8").toString());


    @Autowired
    PushDataMapper pushDataMapper;

    @Autowired
    GateProfileConfig gateProfileConfig;
//
//    private ExecutorService service = new ThreadPoolExecutor(5, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new UpdateThreadFactory());
//    private volatile boolean initOK = false;
//    private Map<String, String> cache = new ConcurrentHashMap<String, String>();
//
//    public static class UpdateThreadFactory implements ThreadFactory {
//
//        private static int threadInitNumber = 0;
//
//        private static synchronized int nextThreadNum() {
//            return threadInitNumber++;
//        }
//
//        @Override
//        public Thread newThread(Runnable r) {
//            return new Thread(r, "Thread-Segment-Update-" + nextThreadNum());
//        }
//    }

    @Override
    public int pushFileToDist(String fileName, String content) {
        try {
            File file = new File(gateProfileConfig.getSendPath() + File.separator + fileName + ".xml");
            if (!file.exists()) {
                file.createNewFile();
            } else {
                file.delete();
                file.createNewFile();
            }

            File textFile = new File(gateProfileConfig.getSendPath() + File.separator + fileName + ".txt");
            if (!textFile.exists()) {
                textFile.createNewFile();
            } else {
                textFile.delete();
                textFile.createNewFile();
            }

            FileWriter fw = new FileWriter(file, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.flush();
            bw.close();
            fw.close();


            FileWriter tfw = new FileWriter(textFile, true);
            BufferedWriter tbw = new BufferedWriter(tfw);
            tbw.write(content);
            tbw.flush();
            tbw.close();
            tfw.close();
            return 1;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int pushFileToDistMulti(String guid, String fileName, String content) {
        PushData data = new PushData();
        Date date = new Date();
        data.setId(UUID.fastUUID().toString(true))
                .setIntime(date).setFilename(fileName)
                .setGuid(guid).setFinished(0).setSend(0)
                .setSuccess(0).setFilecontent(content);
        data.setOrdercode("");
        pushDataMapper.insertPushData(data);
        try {


            File file = new File(gateProfileConfig.getSendPath() + File.separator + fileName + ".xml");
            if (!file.exists()) {
                file.createNewFile();
            } else {
                file.delete();
                file.createNewFile();
            }

            BufferedWriter writer = null;
            FileOutputStream writerStream = new FileOutputStream(file);
            writer = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8"));
            writer.write(content);
            writer.flush();
            writer.close();
            logger.info("写入成功,{}", file.getName());

            file.renameTo((new File(gateProfileConfig.getSendPath() + File.separator + fileName + ".xml")));

            logger.info("文件:{},已重命名到{}路径下", file.getName(), gateProfileConfig.getSendPath());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();

        }

        return 0;
    }

    @Override
    public int pushFileToTJSea(String guid, String fileName, String content, String orderCode) {
        PushData data = new PushData();
        Date date = new Date();
        data.setId(UUID.fastUUID().toString(true))
                .setIntime(date).setFilename(fileName)
                .setGuid(guid).setFinished(0).setSend(0)
                .setSuccess(0).setFilecontent(content);
        data.setOrdercode(orderCode);
        pushDataMapper.insertPushData(data);
        try {


            File file = new File(gateProfileConfig.getSendPath() + File.separator + fileName + ".xml");
            if (!file.exists()) {
                file.createNewFile();
            } else {
                file.delete();
                file.createNewFile();
            }

            BufferedWriter writer = null;
            FileOutputStream writerStream = new FileOutputStream(file);
            writer = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8"));
            writer.write(content);
            writer.flush();
            writer.close();
            logger.info("写入成功,{}", file.getName());

            file.renameTo((new File(gateProfileConfig.getSendPath() + File.separator + fileName + ".xml")));

            logger.info("文件:{},已重命名到{}路径下", file.getName(), gateProfileConfig.getSendPath());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();

        }

        return 0;
    }


    @Override
    public int pushBackFile(Map<String, String> content) {
        RequestBuilder builder = RequestBuilder.post();
        Date date = new Date();
        ArrayList<PushData> datas = new ArrayList<>();
        if (content != null && content.size() > 0) {
            Set<Map.Entry<String, String>> entrySet = content.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                String key = entry.getKey();
                String value = entry.getValue();
                // 请求天津服务器
                HttpUriRequest httpUriRequest = builder
                        .setHeader(xmlHeader).addHeader("seaId", key).addHeader("md5", "1")
                        .setUri(gateProfileConfig.getRemoteUrl())
                        .setEntity(new StringEntity(value, Charset.forName("utf-8")))
                        .build();
                CloseableHttpResponse result = LocalHttpClient.execute(httpUriRequest);
                int statusCode = result.getStatusLine().getStatusCode();
                if (statusCode == 200) {

                    PushData pushData = new PushData();
                    pushData.setGuid(key + "WLYS").setPushtime(date).setSend(1);
                    datas.add(pushData);
                }
            }
            if (datas != null && datas.size() > 0) {
                int i = pushDataMapper.batchSendOkGUID(datas);
            }
        }
        return 0;
    }

    @Override
    public int pushBackFile2(List<BackToRecord> records) {
        RequestBuilder builder = RequestBuilder.post();
        Date date = new Date();
        ArrayList<PushData> datas = new ArrayList<>();
        if (records != null && records.size() > 0) {
            for (BackToRecord record : records) {
                HttpUriRequest httpUriRequest = builder
                        .setHeader(xmlHeader)
                        .setUri(gateProfileConfig.getRemoteUrl()+"/"+record.getOrderCode())
                        .setEntity(new StringEntity(record.getContent(), Charset.forName("utf-8")))
                        .build();
                CloseableHttpResponse result = LocalHttpClient.execute(httpUriRequest);
                int statusCode = result.getStatusLine().getStatusCode();
                if (statusCode == 200) {

                    PushData pushData = new PushData();
                    pushData.setGuid(record.getGuid()).setPushtime(date).setSend(1);
                    datas.add(pushData);
                }
            }
            if (datas != null && datas.size() > 0) {
                int i = pushDataMapper.batchSendOkGUID(datas);
            }
        }
        return 0;
    }

    @Override
    public int updatePushDataFile(List<BackToRecord> records) {
        logger.info("开始更新数据{}", records);
        if (records != null && records.size() > 0) {
            List<String> collect = records.stream().map(BackToRecord::getGuid).collect(Collectors.toList());
            List<PushData> pushData = pushDataMapper.selectByIdList(collect);
            if (pushData != null && pushData.size() > 0) {
                Date date = new Date();
                for (BackToRecord record : records) {
                    record.setBackTime(new Date(record.getLastModified()));
                    record.setUptime(date);
                }
                int i = pushDataMapper.batchBackFile(records);
            } else {
                for (BackToRecord record : records) {
                    record.setId(UUID.fastUUID().toString(true));
                }
                pushDataMapper.batchInsertPushData2(records);
            }
        }
        logger.info("更新数据完成");
        pushBackFile2(records);
        return 0;
    }

    @Override
    public int moveOkFiles(List<File> files) {
        if (files != null && files.size() > 0) {
            for (File file : files) {

                if (file.renameTo(new File(gateProfileConfig.getMovePath() + file.getName()))) {
                    logger.info("文件11111:{},已正常移动到 {},文件夹下", file.getName(), gateProfileConfig.getMovePath());
                } else {
                    File beFile = new File(gateProfileConfig.getMovePath() + file.getName());
                    if (beFile.exists()) {
                        logger.info("文件222222:{},已正常移动到 {},文件夹下", file.getName(), gateProfileConfig.getMovePath());
                        file.delete();
                    } else {
                        logger.info("文件:{},移动到 {},失败", file.getName(), gateProfileConfig.getMovePath());
                    }
                }
            }
        }
        return 0;
    }

}
